package cc.bukkitPlugin.banitem.api;

import java.lang.reflect.Method;
import java.util.HashSet;

import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;

import cc.bukkitPlugin.banitem.BanItem;
import cc.bukkitPlugin.banitem.util.BINMSUtil;
import cc.bukkitPlugin.util.ClassUtil;

public class ModTConstruct extends AMod{

    protected static Method method_TConstructAPI_getInventoryWrapper=null;
    protected static Method method_IPlayerExtendedInventoryWrapper_getKnapsackInventory=null;
    protected static Method method_IPlayerExtendedInventoryWrapper_getAccessoryInventory=null;
    protected static boolean enable=false;

    static{
        Class<?> tInvAPI=null;
        try{
            tInvAPI=Class.forName("tconstruct.api.TConstructAPI");
            method_TConstructAPI_getInventoryWrapper=tInvAPI.getMethod("getInventoryWrapper",BINMSUtil.clazz_EntityPlayer);
            Class<?> wrapper=method_TConstructAPI_getInventoryWrapper.getReturnType();
            method_IPlayerExtendedInventoryWrapper_getKnapsackInventory=wrapper.getMethod("getKnapsackInventory",BINMSUtil.clazz_EntityPlayer);
            method_IPlayerExtendedInventoryWrapper_getAccessoryInventory=wrapper.getMethod("getAccessoryInventory",BINMSUtil.clazz_EntityPlayer);
            ModTConstruct.enable=true;
        }catch(Exception ex){
            if(!(ex instanceof ClassNotFoundException))
                BanItem.severe("初始化匠魂模块时发生了异常",ex);
        }
    }

    @Override
    public HashSet<Inventory> getInventorys(Player pPlayer){
        if(pPlayer==null)
            return null;
        Object enityPlayer=ClassUtil.invokeMethod(pPlayer,BINMSUtil.method_CraftPlayer_getHandle);
        if(enityPlayer==null)
            return null;
        Object invWrapper=ClassUtil.invokeStaticMethod(method_TConstructAPI_getInventoryWrapper,enityPlayer);
        HashSet<Object> NMSInvs=new HashSet<>();
        NMSInvs.add(ClassUtil.invokeMethod(invWrapper,method_IPlayerExtendedInventoryWrapper_getKnapsackInventory,enityPlayer));
        NMSInvs.add(ClassUtil.invokeMethod(invWrapper,method_IPlayerExtendedInventoryWrapper_getAccessoryInventory,enityPlayer));
        HashSet<Inventory> tInvs=new HashSet<>();
        for(Object sNMSInv : NMSInvs){
            if(sNMSInv==null)
                continue;
            Inventory tInv=(Inventory)ClassUtil.getInstance(BINMSUtil.clazz_CraftInventory,BINMSUtil.clazz_IInventory,sNMSInv);
            if(tInv!=null)
                tInvs.add(tInv);
        }
        return tInvs;
    }

    @Override
    public boolean initSuccess(){
        return ModTConstruct.enable;
    }

}
